import re
import tkinter
from tkinter import messagebox

winMain = tkinter.Tk()			#创建主窗口
winMain.title('登陆')			#设置主窗口标题
screen_width = winMain.winfo_screenwidth()
screen_height = winMain.winfo_screenheight()
windowidth = 800
windowheight = 600
x = (screen_width-windowidth) // 2
y = (screen_height - windowheight) //2
winMain.geometry(f'{windowidth}x{windowheight}+{x}+{y}')	#设置窗口几何属性(宽x高+左+上)

frame =tkinter.Frame(winMain,padx=100,pady=100)
frame.pack()



lbl_username =tkinter.Label(frame,text='用户名')
username = tkinter.Entry(frame,validate='focusout',validatecommand=lambda:checkUsername())
lbl_username_span =tkinter.Label(frame,text='',width=20,)
lbl_username.grid(row=0,column=0)
username.grid(row=0,column=1)
lbl_username_span.grid(row=0,column=2)


lbl_pwd =tkinter.Label(frame,text='密 码')
pwd = tkinter.Entry(frame,show='*')
lbl_pwd.grid(row=1,column=0)
pwd.grid(row=1,column=1)

login=tkinter.Button(frame,text='登陆',command=lambda:show())
login.grid(row=2,column=1)

cancel=tkinter.Button(frame,text='退出',command=lambda:logout())
cancel.grid(row=3,column=1)

# winSub = tkinter.Toplevel(winMain) 	#创建子窗口
# winSub.title('child')			#子窗口标题
# winSub.geometry('250x200')		#子窗口几何属性
# winSub.mainloop()			#显示并进入消息循环
# 显示并进入消息循环, 等待用户输入, 窗口关闭后这个循环结束

def checkUsername():
    str_name = username.get().strip()
    if not re.match(r'^[a-zA-Z0-9_-]{4,16}$', str_name):
        lbl_username_span.config(text='用户名格式不正确', fg='red')
        return False  # 验证失败返回False
    else:
        lbl_username_span.config(text='')
        return True


def show():
    if 'admin'==username.get().strip() and '123456'==pwd.get().strip():
        print('登陆成功')
        main = tkinter.Toplevel(winMain)
        main.title('登陆成功')
        main.geometry('900x600')
        main.grab_set()
        main.mainloop()

    else:
        messagebox.showinfo('登陆失败', '用户名或密码错误')

def logout():
    if messagebox.askyesno('退出', '确定退出吗?'):
        winMain.quit()


winMain.mainloop()

# winMain.title('按钮(Button)示例')
# winMain.geometry('400x300') #创建按钮, 并使用pack进行布局管理(显示位置)
# btn1 = tkinter.Button(winMain, text='按钮1')
# btn1.pack()
# def onBtn2Click():		#定义按钮点击事件函数
#     print('按钮2点击')	#创建并绑定事件
# btn2 = tkinter.Button(winMain, text="按钮2", command=onBtn2Click)
# btn2.place(x=100, y=30)	#place()方法进行几何管理,在窗口里显示
# #创建红色文字按钮并指定位置大小进行布局
# btn3 = tkinter.Button(winMain, text='按钮3', fg='red')
# btn3.place(x=150, y=60, width=200, height=100)
# winMain.mainloop()	#显示并进入消息循环